package org.gzc.hash;


/**
 * @Description: 哈希表的简单实现
 * 根据 员工ID 获取员工信息
 * @Author: guozongchao
 * @Date: 2020/8/12 21:46
 */
public class HashTab {
    private Node[] elemTab;
    private int size;
    private class Node{
        private Emp value;
        private Node next;

        public Node(Emp value) {
            this.value = value;
        }

        public Emp getValue() {
            return value;
        }

        public void setValue(Emp value) {
            this.value = value;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

    public HashTab(int size) {
        this.size=size;
        this.elemTab=new Node[size];
    }

    public void put(int key,Emp value) {
        if (value == null) {
            throw new NullPointerException();
        }
        int index = hashFun(key);
        Node node = new Node(value);
        if (elemTab[index] == null) {
            elemTab[index]=node;
        }else{
            Node curr=elemTab[index];
            node.setNext(curr);
            elemTab[index] = node;
        }
    }

    public Emp get(int key) {
        int index = hashFun(key);
        Node curr = elemTab[index];
        while(curr!=null){
            if (curr.value.getId() == key) {
                break;
            }
            curr=curr.next;
        }
        return curr.value;
    }

    public void display(){
        Node curr;
        for (int i = 0; i < size; i++) {
            curr=elemTab[i];
            System.out.print("第"+(i+1)+"个链表的数据:"+(curr==null?"空空如也~":""));
            while (curr != null) {
                System.out.print(curr.value);
                if(curr.next!=null){
                    System.out.print("-->");
                }
                curr=curr.next;
            }
            System.out.println();
        }
    }

    private int hashFun(int key) {
        return key % size;
    }
}

class Emp{
    private  int id;
    private String name;
    private String address;

    public Emp(int id, String name, String address) {
        this.id=id;
        this.name=name;
        this.address=address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}